package com.itcg.springboot03deptemptest.controller;


import com.itcg.springboot03deptemptest.pojo.Dept;
import com.itcg.springboot03deptemptest.pojo.Result;
import com.itcg.springboot03deptemptest.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @PutMapping
    public Result update(@RequestBody Dept dept) {
        if (null == dept) {
            return Result.error("修改失败");
        }
        deptService.updates(dept);
        return Result.success("修改成功");
    }

    @DeleteMapping("/{id}")
    public Result deletes(@PathVariable Integer id) {
        if (id == null || id <= 0) {
            return Result.error(" id 为不合法参数");
        }
        deptService.deletes(id);
        return Result.success("删除成功");
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        if (id == null || id <= 0) {
            return Result.error(" id 为不合法参数");
        }
        Dept dept = deptService.findById(id);
        return Result.success(dept);
    }

    @GetMapping("whenemp/{id}")
    public Result findWhenEmpById(@PathVariable Integer id) {
        if (id == null || id <= 0) {
            return Result.error(" id 为不合法参数");
        }
        Dept dept = deptService.findWhenEmpById(id);
        if (dept == null) {
            return Result.success("该部门不存在");
        }
        return Result.success(dept);
    }

    @PostMapping
    public Result inserts(@RequestBody Dept dept) {
        if (null == dept || "".equals(dept.getName())) {
            return Result.error("添加失败,name属性为空");
        }
        deptService.inserts(dept);
        return Result.success("添加成功");
    }

    @GetMapping
    public Result findAll() {
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }
}
